<?php

namespace app\admin\controller\weblog;

use app\common\controller\Backend;

/**
 * 日志记录管理
 *
 * @icon fa fa-circle-o
 */
class Log extends Backend
{
    
    /**
     * Log模型对象
     * @var \app\admin\model\weblog\Log
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\weblog\Log;
    }

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            \think\Debug::remark('begin');
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model->where($where)->count('id');

            //\think\Debug::remark('begin');
            //$list = $this->model
            //    ->with(['weblogsite','weblogspider'])
            //    ->where($where)
            //    ->order($sort, $order)
            //    ->limit($offset, $limit)
            //    ->select();
            //
            //foreach ($list as $row) {
            //    $row->getRelation('weblogsite')->visible(['id', 'name', 'describe', 'log_file']);
            //    $row->getRelation('weblogspider')->visible(['id', 'name', 'keyword']);
            //}
            //$list = collection($list)->toArray();
            //\think\Debug::remark('end');
            //show_bug(\think\Debug::getRangeTime('begin', 'end') . 's---' . $this->model->getLastSql());
            //优化前37.615671s


            //百万级数据查询优化，毫秒级查询速度，但会损失自定义排序功能/和关联查询
            $min_id = $this->model->order('id', $order)->value('id');
            if ($order == 'desc') {
                $last_max_id = $min_id - $offset;
            } else {
                $last_max_id = $min_id + $offset;
            }
            $operator = ['asc' => 'egt', 'desc' => 'elt'];
            $list = $this->model
                ->where($where)
                ->where(['id' => [$operator[$order], $last_max_id]])
                ->order('id', $order)
                ->limit($limit)
                ->select();
            $list = collection($list)->toArray();

            //\think\Debug::remark('end');
            //show_bug(\think\Debug::getRangeTime('begin', 'end') . 's---' . $this->model->getLastSql());
            //优化后0.040682s

            foreach ($list as &$row) {
                $row['weblogsite']   = \think\Db::name('weblog_site')->where(['id' => $row['site_id']])->find();
                $row['weblogspider'] = \think\Db::name('weblog_spider')->where(['id' => $row['spider_id']])->find();
            }
            unset($row);

            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 站点占比统计
     * @author Created by Xing <464401240@qq.com>
     */
    public function site()
    {
        if ($this->request->isAjax()) {
            $siteStatisticsModel = new \app\admin\model\weblog\SiteStatistics();
            $site = \app\admin\model\weblog\Site::all();
            $siteData = $visitsCount = $ipCount = [];

            foreach ($site as $row) {
                $siteRow = $siteStatisticsModel->where(['site_id' => $row->id])->find();
                if (empty($siteRow)) {
                    continue;//没有请求记录的站点不显示
                }
                $siteData[] = $row->name;
                $visitsCount[] = [
                    'value' => $siteRow->visits_count,
                    'name'  => $row->name,
                ];
                $ipCount[] = [
                    'value' => $siteRow->ip_count,
                    'name'  => $row->name,
                ];
            }

            $data = [
                'siteData' => $siteData,
                'visitsCount' => $visitsCount,
                'ipCount' => $ipCount,
            ];
            $this->success('ok', null, $data);
        }
        return $this->view->fetch();
    }

    /**
     * 蜘蛛占比统计
     * @author Created by Xing <464401240@qq.com>
     */
    public function spider()
    {
        if ($this->request->isAjax()) {
            $where = [];
            $site_id = $this->request->request('site_id');
            if ($site_id) {
                $where['site_id'] = $site_id;
            } else {
                $siteModel = new \app\admin\model\weblog\Site;
                $site_ids  = $siteModel->value('GROUP_CONCAT(id)');
                if ($site_ids) {
                    $where['site_id'] = ['in', $site_ids];
                }
            }
            $spider = \app\admin\model\weblog\Spider::all();
            $spider[] = ['id' => 0, 'name' => '其他'];
            $spiderData = $visitsCount = [];
            $spiderModel = new \app\admin\model\weblog\SpiderStatistics();
            foreach ($spider as $row) {
                $where['spider_id'] = $row['id'];
                $visits_count = $spiderModel->where($where)->value('visits_count');
                if (!$visits_count) {
                    continue; //没有数据的蜘蛛不显示
                }

                $spiderData[]  = $row['name'];
                $visitsCount[] = $visits_count;
            }
            $data = [
                'spiderData'  => $spiderData,
                'visitsCount' => $visitsCount
            ];
            $this->success('ok', null, $data);
        }
        return $this->view->fetch();
    }

    /**
     * URL流量统计
     * @author Created by Xing <464401240@qq.com>
     */
    public function url()
    {
        if ($this->request->isAjax()) {
            $urlModel = new \app\admin\model\weblog\UrlStatistics();
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $urlModel->where($where)->group('url')->order($sort, $order)->count('id');
            $list  = $urlModel->where($where)->group('url')
                ->field('sum(visits_count) as visits_count,sum(ip_count) as ip_count,url,id')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * IP流量统计
     * @author Created by Xing <464401240@qq.com>
     */
    public function ip()
    {
        if ($this->request->isAjax()) {
            $ipModel = new \app\admin\model\weblog\IpStatistics();
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $ipModel->where($where)->group('ip')->order($sort, $order)->count('id');
            $list = $ipModel->with(['weblogspider'])
                ->group('ip')
                ->where($where)
                ->field('sum(visits_count) as visits_count')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $row) {
                $row->getRelation('weblogspider')->visible(['name']);
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 访问状态统计
     * @author Created by Xing <464401240@qq.com>
     */
    public function code()
    {
        if ($this->request->isAjax()) {
            $codeModel = new \app\admin\model\weblog\CodeStatistics();
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $codeModel->where($where)->order($sort, $order)->count('id');
            $list  = $codeModel->with(['weblogcode'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $row) {
                $row->getRelation('weblogcode')->visible(['describe']);
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }
}
